package com.yanyeori.framework.core.context;

import com.yanyeori.framework.core.util.IdUtil;
import lombok.*;

import java.io.Serializable;
import java.util.Date;

/**
 * 跟踪链路上下文
 *
 * @author chenkuan 2022/10/28
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class TraceContext implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 链路ID
     */
    private String traceId;

    /**
     * 创建时间
     */
    private Date time;

    public static TraceContext get(boolean initIfNull) {
        TraceContext context = ContextHolder.TRACE_CONTEXT_HOLDER.get();
        if (initIfNull && context == null) {
            context = new TraceContext(IdUtil.simpleUUID(), new Date());
            set(context);
        }
        return context;
    }

    public static void set(TraceContext context) {
        ContextHolder.TRACE_CONTEXT_HOLDER.set(context);
    }

    public static void clear() {
        ContextHolder.TRACE_CONTEXT_HOLDER.remove();
    }
}
